alter proc rpt_AI_DailyRevenueFB
	@date datetime
as
begin
	declare @firstDate as datetime
	set @firstDate = DATEADD(mm, DATEDIFF(mm, 0, @date), 0)		
	
	select wh.WhsCode, wh.WhsName, SUM(FoodRevenue) FoodRevenue, 
				SUM(BeveRevenue) BeveRevenue, SUM(mtdFoodRevenue) mtdFoodRevenue, 
				SUM(mtdBeveRevenue) mtdBeveRevenue, SUM(T.Covers) Covers, SUM(T.mtdCovers) mtdCovers
				 from OWHS wh left join	
		(	
		select v1.WhsCode, tb.ItmsGrpCod, 
		SUM(v1.LineTotal) FoodRevenue, 0 BeveRevenue, 0 mtdFoodRevenue, 0 mtdBeveRevenue, 
		count(distinct v1.DocEntry) Covers, 0 mtdCovers
		from INV1 v1
		join OINV iv on v1.DocEntry = iv.DocEntry
		left join OITM tm on v1.ItemCode = tm.ItemCode
		left join OITB tb on tm.ItmsGrpCod = tb.ItmsGrpCod
		where tb.ItmsGrpCod = '101' and iv.DocDate = @date
		group by v1.WhsCode, tb.ItmsGrpCod
		
		union all
		
		select v1.WhsCode, tb.ItmsGrpCod, 
		0 FoodRevenue, SUM(v1.LineTotal) BeveRevenue, 0 mtdFoodRevenue, 0 mtdBeveRevenue,
		count(distinct v1.DocEntry) Covers, 0 mtdCovers
		 from INV1 v1
		join OINV iv on v1.DocEntry = iv.DocEntry
		left join OITM tm on v1.ItemCode = tm.ItemCode
		left join OITB tb on tm.ItmsGrpCod = tb.ItmsGrpCod
		where tb.ItmsGrpCod = '102' and iv.DocDate = @date
		group by v1.WhsCode, tb.ItmsGrpCod
		
		union all
		
		select v1.WhsCode, tb.ItmsGrpCod, 
		0 FoodRevenue, 0 BeveRevenue, SUM(v1.LineTotal) mtdFoodRevenue, 0 mtdBeveRevenue,
		0 Covers, count(distinct v1.DocEntry) mtdCovers 
		from INV1 v1
		join OINV iv on v1.DocEntry = iv.DocEntry
		left join OITM tm on v1.ItemCode = tm.ItemCode
		left join OITB tb on tm.ItmsGrpCod = tb.ItmsGrpCod
		where tb.ItmsGrpCod = '101' and iv.DocDate between @firstDate and @date
		group by v1.WhsCode, tb.ItmsGrpCod
		
		union all
		
		select v1.WhsCode, tb.ItmsGrpCod, 
		0 FoodRevenue, 0 BeveRevenue, 0 mtdFoodRevenue, SUM(v1.LineTotal) mtdBeveRevenue, 
		0 Covers, count(distinct v1.DocEntry) mtdCovers  
		from INV1 v1
		join OINV iv on v1.DocEntry = iv.DocEntry
		left join OITM tm on v1.ItemCode = tm.ItemCode
		left join OITB tb on tm.ItmsGrpCod = tb.ItmsGrpCod
		where tb.ItmsGrpCod = '102' and iv.DocDate between @firstDate and @date
		group by v1.WhsCode, tb.ItmsGrpCod
	) T on T.WhsCode = wh.WhsCode
	group by wh.WhsCode, wh.WhsName

end

-- rpt_AI_DailyRevenueFB '07-26-2013'


-- select count(iv.DocEntry) from OINV iv
